
package newfragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.Toast;

import com.example.dell.avtivity.InPassword;
import com.example.dell.avtivity.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import NetRequest.SendRuest;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by dell on 2017/1/26.
 */

public class PhoneInfragment extends Fragment {

    private String TAG = "TAG";
    private String phone = "";
    private String code = "";
    private String status = "";
    private String msg = "";
    private String token = "";
    private View focusView = null;
    private View view = null;
    SendRuest sr = null;
    private String password = "";
    private int valid = 0;


    // UIView
    private AutoCompleteTextView tel;
    private EditText words;
    private Button getNums;
    private Button login_button_phonein;
    private ScrollView scrollView;
    private ProgressBar progressBar;

    public static final int SENGCODESUCESS = 1;
    public static final int SENGCODEFAILED = 2;
    public static final int CODETRUE = 3;
    public static final int CODEFALSE = 4;
    public static final int LOGINTRUE = 5;
    public static final int LOGINFALSE = 6;
    public static final int REGISTERTRUE = 7;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SENGCODESUCESS:
                    CountTimer ct = new CountTimer(60000, 1000);
                    ct.start();
                    Toast.makeText(view.getContext(), "已发送", Toast.LENGTH_SHORT).show();
                    break;
                case SENGCODEFAILED:
                    Toast.makeText(view.getContext(), "发送失败", Toast.LENGTH_SHORT).show();
                    break;
                case CODETRUE:
                    words.setText("");
                    Log.d(TAG, "CODE is true");
                    break;
                case CODEFALSE:
                    words.setText("");
                    Toast.makeText(view.getContext(), "验证码错误", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "CODE is error");
                    showProgress(false);
                    break;
                case LOGINTRUE:
                    Toast.makeText(view.getContext(), "欢迎回来，正在登陆", Toast.LENGTH_SHORT).show();
                    progressBar.setVisibility(View.GONE);
                    Log.d(TAG, "login_token" + token);
                    break;
                case LOGINFALSE:
                    Log.d(TAG, "登录失败");
                    break;
                case REGISTERTRUE:
                    showProgress(false);
                    Intent intent = new Intent(view.getContext(), InPassword.class);
                    intent.putExtra("phone", phone);
                    startActivity(intent);
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragmen_phonein, container, false);
        tel = (AutoCompleteTextView) view.findViewById(R.id.tel);
        words = (EditText) view.findViewById(R.id.words);
        getNums = (Button) view.findViewById(R.id.GetNums);
        login_button_phonein = (Button) view.findViewById(R.id.login_button_phonein);
        scrollView = (ScrollView) view.findViewById(R.id.phone_form);
        progressBar = (ProgressBar) view.findViewById(R.id.phonein_progress);
        sr = new SendRuest(view.getContext());
//        words.setEnabled(false);
       /*
       获取验证码按钮事件
        */
        getNums.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(final View view) {
                phone = tel.getText().toString();
                if (isTelValid(phone)) {
                    SendRuest sr = new SendRuest(view.getContext());
                    sr.SendKey_Login(phone, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
//                            Toast.makeText(view.getContext(), "验证码返回error", Toast.LENGTH_SHORT).show();
                            Message message = new Message();
                            message.what = SENGCODEFAILED;
                            handler.sendMessage(message);
                            Log.d(TAG, "RESPONSE FAILED");
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            try {
                                String responsedata = response.body().string();
                                JSONObject jsonObject = new JSONObject(responsedata);
                                String status = jsonObject.getString("error_code");
                                Log.d("TAG", responsedata);
                                if (responsedata.isEmpty()||!status.equals("0")) {
                                    Message message = new Message();
                                    message.what = SENGCODEFAILED;
                                    handler.sendMessage(message);
                                } else {
                                    Message message = new Message();
                                    message.what = SENGCODESUCESS;
                                    handler.sendMessage(message);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Message message = new Message();
                                message.what = SENGCODEFAILED;
                                handler.sendMessage(message);
                            }
                        }
                    });
                } else {
                    Toast.makeText(view.getContext(), "请填写正确的手机号码", Toast.LENGTH_SHORT).show();
                }
            }
        });



        /*
        登录
         */
        login_button_phonein.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                code = words.getText().toString();
                phone = tel.getText().toString();
                if (attemptLogin() == 2) {
                    // 判断验证码是否正确
                    sr.isKeytrue(phone, code, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.d(TAG, "isKeytrue:" + "返回response失败");
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String responsedata = response.body().string();
                            try {
                                JSONObject jsonObject = new JSONObject(responsedata);
                                status = jsonObject.getString("error_code");
                                if (status.equals("0")) {
                                    //验证码正确，直接登录
                                    Message message = new Message();
                                    message.what = CODETRUE;
                                    handler.sendMessage(message);
                                    loginto(sr);
                                } else {
                                    Message message = new Message();
                                    message.what = CODEFALSE;
                                    handler.sendMessage(message);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Message message = new Message();
                                message.what = CODEFALSE;
                                handler.sendMessage(message);
                            }
                        }
                    });
                }
            }
        });
        return view;
    }

    /*
    手机直接登录
     */
    public void loginto(SendRuest sr) {
        sr.SendRuest_LoginWithPhone(phone, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsedata1 = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(responsedata1);
                    msg = jsonObject.getString("error_code");
                    //手机号码已经注册，直接登陆
                    if (msg.equals("0")) {
                        Message message = new Message();
                        message.what = LOGINTRUE;
                        handler.sendMessage(message);
                        token = jsonObject.getString("token");
                        //注册
                    } else if (msg.equals("error")) {
                        Message message = new Message();
                        message.what = REGISTERTRUE;
                        handler.sendMessage(message);
                    } else {
                        Message message = new Message();
                        message.what = LOGINFALSE;
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }


    /*
    登录前检查
     */
    private int attemptLogin() {

        tel.setError(null);
        words.setError(null);
        String Tel = tel.getText().toString();
        String Words = words.getText().toString();

        int cancel = 0;
        /*
        验证验证码格式
         */
        if (TextUtils.isEmpty(Words) || isWordsValid(Words)) {
            words.setError(getString(R.string.error_field_words_false));
            focusView = words;
            cancel = 1;
        }

        if (TextUtils.isEmpty(Tel) || !isTelValid(Tel)) {
            tel.setError(getString(R.string.error_field_tel_false));
            focusView = tel;
            cancel = 1;
        }

        if (cancel == 1) {
            focusView.requestFocus();
        } else {
            cancel = 2;
            showProgress(true);
        }
        return cancel;
    }

    /*
    验证手机格式
     */
    private boolean isTelValid(String t) {

        Pattern p = Pattern.compile("^(13[0-9]|14[57]|15[0-35-9]|17[6-8]|18[0-9])[0-9]{8}$");
        Matcher m = p.matcher(t);
        return m.matches();
    }

    /*
    验证验证码合法
     */
    private boolean isWordsValid(String password) {
        return password.length() != 6;
    }

    /*
      显示进度条
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
//        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(focusView.getWindowToken(), 0);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            scrollView.setVisibility(show ? View.GONE : View.VISIBLE);
            scrollView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    scrollView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
            progressBar.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
//                    progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
            scrollView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /*
    获取验证码倒计时
     */
    private class CountTimer extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public CountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }


        @Override
        public void onTick(long millisUntilFinished) {
            getNums.setClickable(false);
            getNums.setText(millisUntilFinished / 1000 + "s后可再获取");
            getNums.setBackgroundResource(R.drawable.buttonunclickable);
        }

        @Override
        public void onFinish() {
            getNums.setClickable(true);
            getNums.setText("获取验证码");
            getNums.setBackgroundResource(R.drawable.button);
        }
    }

}

